// 包含n个reducer函数：根据当前得到的state和action 返回一个新的state
import { combineReducers } from 'redux'
import {
  AUTH_SUCCESS,
  ERROR_MSG,
  RESET_USER,
  RECEIVE_USER,
  RECEIVE_USER_LIST,
  RECEIVE_MSG_LIST,
  RECEIVE_MSG,
  MSG_READ
} from './action-type'
import { getRedirectTo } from '../utils/index'
const initUser = {
  username: '',
  type: '',
  msg: '',
  redirectTo: '' //需要自动重定向的路由路径
}
// 产生user状态的reducer
function user(state = initUser, action) {
  switch (action.type) {
    case AUTH_SUCCESS:
      const { type, header } = action.data
      return { ...action.data, redirectTo: getRedirectTo(type, header) }
    case ERROR_MSG:
      return { ...state, msg: action.data }
    case RESET_USER: //data是msg
      return { ...initUser, msg: action.data }
    case RECEIVE_USER: //data是user
      return action.data
    default:
      return state
  }
}

const inituserList = []
// 产生userList状态的reducer
function userList(state = inituserList, action) {
  switch (action.type) {
    case RECEIVE_USER_LIST:
      return action.data
    default:
      return state
  }
}

// 产生聊天状态的reducer
const initChat = {
  users: {}, // 所有用户信息的对象
  chatMsgs: [], //当前用户所有相关的msg的数组
  unReadCount: 0 //总的未读数量
}
function Chat(state = initChat, action) {
  switch (action.type) {
    case RECEIVE_MSG_LIST:
      const { users, chatMsgs, userId } = action.data
      return {
        users,
        chatMsgs,
        unReadCount: chatMsgs.reduce(
          (preTotal, msg) =>
            preTotal + (!msg.read && msg.to === userId ? 1 : 0),
          0
        )
      }
    case RECEIVE_MSG:
      const { chatMsg } = action.data
      return {
        users: state.users,
        chatMsgs: [...state.chatMsgs, chatMsg],
        unReadCount:
          state.unReadCount +
          (!chatMsg.read && chatMsg.to === action.data.userId ? 1 : 0)
      }
    case MSG_READ:
      const { count, from, to } = action.data
      return {
        users: state.users,
        chatMsgs: state.chatMsgs.map(msg => {
          if (msg.from === from && msg.to === to && !msg.read) {
            // 需要更新
            return { ...msg, read: true }
          } else {
            return msg
          }
        }),
        unReadCount: state.unReadCount - count
      }
    default:
      return state
  }
}
export default combineReducers({ user, userList, Chat })
